<template>
    <div class="login-container">
        <div class="logo">
            <img src="../assets/logo.png" alt="">
        </div>
        <el-form :model="loginFrom" :rules="loginFromRules" ref="loginFromRef" label-width="0px" class="loginFrom">
            <el-form-item  prop="username">
                <el-input v-model="loginFrom.username">
                    <i slot="prefix" class="iconfont icon-user"></i>
                </el-input>
            </el-form-item>
            <el-form-item  prop="password">
                <el-input v-model="loginFrom.password" type="password">
                    <i slot="prefix" class="iconfont icon-3702mima"></i>
                </el-input>
            </el-form-item>
        </el-form>
        <div class="btn">
            <el-button type="primary" @click="login">登录</el-button>
            <el-button type="info" @click="resetForm">重置</el-button>
        </div>
    </div>
</template>
<script>
export default {
  data() {
    return {
      loginFrom: {
        username: 'admin',
        password: '123456'
      },
      loginFromRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 12, message: '长度在 5 到 12 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 重置表单按钮
    resetForm() {
      this.$refs.loginFromRef.resetFields()
    },
    login() {
      // 验证表单
      this.$refs.loginFromRef.validate(async vali => {
        if (!vali) return
        // 发起ajax登录请求
        const { data: res } = await this.$http.post('login', this.loginFrom)
        if (res.meta.status !== 200) return this.$message.error('登录失败')
        this.$message.success('登录成功')
        // 登录令牌保存到sessionStorage 给后续接口使用
        window.sessionStorage.setItem('token', res.data.token)
        // 跳转到home页面
        this.$router.push('/home')
      })
    }
  }
}
</script>
<style lang="less" scoped>
.login-container {
  width: 450px;
  height: 304px;
  background-color: #fff;
  position: absolute;
  top: 25%;
  left: 50%;
  transform: translateX(-50%);
  border-radius: 10px;

  .logo {
    width: 130px;
    height: 130px;
    position: absolute;
    left: 50%;
    transform: translateX(-50%) translateY(-40px);
    border: 1px solid #fff;
    background-color: #fff;
    padding: 8px;
    border-radius: 50%;
    box-shadow: 0 0 10px #e3e3e3;
    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      border: 1px solid #fff;
      background-color: #e3e3e3;
    }
  }
  .loginFrom {
    margin-top: 120px;
    padding: 0 15px;
  }
  .btn {
    margin-left: 250px;
  }
}
</style>
